package com.dpl.yyrj.utils;

// LogUtil.java

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;

/**
 * @author: dpl
 * @date: 2025 08 02 16:07
 * @description: 自定义日志工具类，在Android原生Log基础上增加应用版本等信息
 **/
public class LogUtil {

    private static String sAppVersion = "Unknown";
    private static String sAppName = "Unknown";
    private static boolean sIsDebug = true;

    /**
     * 初始化LogUtil，建议在Application中调用
     *
     * @param context 上下文
     * @param isDebug 是否为调试模式
     */
    public static void init(@NonNull Context context, boolean isDebug) {
//        sIsDebug = isDebug;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            sAppVersion = packageInfo.versionName;
            sAppName = context.getApplicationInfo().loadLabel(pm).toString();
        } catch (Exception e) {
            Log.e("LogUtil", "Failed to get app version", e);
        }
    }

    /**
     * 获取日志前缀信息
     *
     * @return 包含应用版本等信息的前缀
     */
    private static String getLogPrefix() {
        return "[" + sAppName + " v" + sAppVersion + " SDK:" + Build.VERSION.SDK_INT + "]";
    }

    /**
     * verbose级别日志
     */
    public static void v(String tag, String msg) {
        if (sIsDebug) {
            Log.v(tag, getLogPrefix() + " " + msg);
        }
    }

    /**
     * debug级别日志
     */
    public static void d(String tag, String msg) {
        if (sIsDebug) {
            Log.d(tag, getLogPrefix() + " " + msg);
        }
    }

    /**
     * info级别日志
     */
    public static void i(String tag, String msg) {
        Log.i(tag, getLogPrefix() + " " + msg);
    }

    /**
     * warn级别日志
     */
    public static void w(String tag, String msg) {
        Log.w(tag, getLogPrefix() + " " + msg);
    }

    /**
     * error级别日志
     */
    public static void e(String tag, String msg) {
        Log.e(tag, getLogPrefix() + " " + msg);
    }

    /**
     * error级别日志，带异常信息
     */
    public static void e(String tag, String msg, Throwable throwable) {
        Log.e(tag, getLogPrefix() + " " + msg, throwable);
    }

    /**
     * 设置是否为调试模式
     */
    public static void setDebug(boolean isDebug) {
        sIsDebug = isDebug;
    }

    /**
     * 获取应用版本
     */
    public static String getAppVersion() {
        return sAppVersion;
    }
}
